package main

import (
	"context"
	"embed"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"wails/nodes/editornode"

	"gitee.com/zhongguo168a/gocodes/datax/reflectx/loader"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"gitee.com/zhongguo168a/gocodes/myx/logx"
	"gitee.com/zhongguo168a/gocodes/myx/logx/logrus"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// 获取屏幕分辨率（Windows）
func getScreenResolution() (int, int) {
	// 使用 wmic 命令获取分辨率
	cmd := exec.Command("wmic", "path", "Win32_VideoController", "get", "CurrentHorizontalResolution,CurrentVerticalResolution")
	output, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println("Error:", err)
		return 1920, 1080 // 默认分辨率
	}

	// 打印输出，查看格式
	fmt.Println("WMIC Output:\n", string(output))

	// 处理输出，去除多余的空格和换行
	lines := strings.Split(string(output), "\n")
	if len(lines) < 2 {
		return 1920, 1080
	}

	// 分辨率值通常在第二行
	resolutionLine := strings.TrimSpace(lines[1])
	var width, height int
	// 格式化为宽度和高度
	_, err = fmt.Sscanf(resolutionLine, "%d %d", &width, &height)
	if err != nil {
		fmt.Println("Error parsing resolution:", err)
		return 1920, 1080 // 默认分辨率
	}

	return width, height
}

//go:embed generate/schema_export/game/game.json
var GameJson embed.FS

func (a *App) initGameJson() error {
	schemamap := map[string]interface{}{}
	{
		data, err := GameJson.ReadFile("generate/schema_export/game/game.json")
		err = json.Unmarshal(data, &schemamap)
		if err != nil {
			return errorx.Wrap(err, fmt.Sprintf("json.Unmarshal"))
		}
	}

	if err := loader.LoadMap(schemamap); err != nil {
		return errorx.Wrap(err, fmt.Sprintf("loader.LoadMap"))
	}

	return nil
}

func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
	if err := a.initGameJson(); err != nil {
		logx.Fail(errorx.Wrap(err, "initGameJson"))
		os.Exit(-1)
	}

	width, height := getScreenResolution()
	fmt.Printf("Screen resolution: %d x %d\n", width, height)

	// 设置窗口大小为屏幕的 80%
	runtime.WindowSetSize(ctx, int(float64(width)*0.8), int(float64(height)*0.8))
	logger := logrus.NewLogger()
	logger.UseFileRotation("log")
	logx.RegisterDefault(logger)

	editornode.Run()
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

func (a *App) MyFunc(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}
